import axios from 'axios';

// Create an Axios instance
const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL, // Base URL from environment variables
    timeout: 5000, // Request timeout
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
});

// Request interceptor
service.interceptors.request.use(
    config => {
        // Do something before request is sent
        // For example, you can add a token here
        // config.headers['Authorization'] = 'Bearer ' + token;
        return config;
    },
    error => {
        // Do something with request error
        console.error(error); // for debug
        return Promise.reject(error);
    }
);

// Response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data;
        // If the custom code is not 200, it is judged as an error.
        // if (res.code !== 200) {
        //     // Handle error
        //     console.error('Error: ' + res.message);
        //     return Promise.reject(new Error(res.message || 'Error'));
        // } else {
        //     return res;
        // }
        if (!res.success) {
            // console.error('Error: ' + res.message);
            return Promise.reject(new Error(res.message || 'Error'));
        } else {
            return res;
        }
    },
    error => {
        console.error('Error: ' + error.message); // for debug
        return Promise.reject(error);
    }
);

export default service;